package com.promise.jokerdream.work.faction

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.response.pc.QueryFactionChallengePCResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 帮派踢馆
class FactionChallengeWork(
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "帮派踢馆"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询帮派挑战信息
            val queryResult = gameApi.queryFactionChallenge()

            queryResult.fold(
                onSuccess = { response ->
                    if (response.isFightTime > 0) {
                        // 挑战时间，执行试炼和挑战
                        executeTrialAndChallenge(response)
                    } else if (response.isAwardTime > 0) {
                        // 领奖时间，执行领奖和排名奖励
                        executeClaimRewards(response)
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                    WorkResult.Failure(exception, exception.message)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 执行试炼和挑战
     */
    private suspend fun executeTrialAndChallenge(queryResponse: QueryFactionChallengePCResponse): WorkResult {
        return try {
            // 计算剩余试炼次数
            val remainingTrialTimes = queryResponse.maxFightNpcTimes - queryResponse.fightNpcTimes

            // 试炼剩余次数次
            repeat(remainingTrialTimes) { index ->
                val trialResult = gameApi.factionChallengeTrial()
                trialResult.fold(
                    onSuccess = { response ->
                        historyManager.addHistory(name, response.getDescription())
                    },
                    onFailure = { exception ->
                        historyManager.addHistory(name, exception.message)
                    }
                )

                // 延个500ms
                kotlinx.coroutines.delay(500)
            }

            // 挑战，一直挑战直到生命值为0
            var currentLifeNum = queryResponse.lifeNum
            while (currentLifeNum > 0) {
                val fightResult = gameApi.factionChallengeFight()
                fightResult.fold(
                    onSuccess = { response ->
                        if (response.msg.startsWith("（败）")) {
                            currentLifeNum -= 1
                        }
                        historyManager.addHistory(name, response.getDescription())
                    },
                    onFailure = { exception ->
                        historyManager.addHistory(name, exception.message)
                        // 挑战失败时停止
                        currentLifeNum = 0
                    }
                )
                // 延个500ms
                kotlinx.coroutines.delay(500)
            }

            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 执行领奖和排名奖励
     */
    private suspend fun executeClaimRewards(queryResponse: QueryFactionChallengePCResponse): WorkResult {
        return try {
            // 检查是否能领奖
            if (queryResponse.canSign > 0) {
                // 领奖
                val claimResult = gameApi.factionChallengeClaimReward()
                claimResult.fold(
                    onSuccess = { response ->
                        historyManager.addHistory(name, response.getDescription())
                    },
                    onFailure = { exception ->
                        historyManager.addHistory(name, exception.message)
                    }
                )

                // 领排名奖励
                val rankClaimResult = gameApi.factionChallengeClaimRankReward()
                rankClaimResult.fold(
                    onSuccess = { response ->
                        historyManager.addHistory(name, response.getDescription())
                    },
                    onFailure = { exception ->
                        historyManager.addHistory(name, exception.message)
                    }
                )
            }
            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}